/* include ---------------------------------------------------------*/
#include "wifi_ap.h"


/* private define -------------------------------------------------*/
#define EXAMPLE_ESP_WIFI_SSID      "MNIAS"
#define EXAMPLE_ESP_WIFI_PASS      "1234567890"
#define EXAMPLE_ESP_WIFI_CHANNEL    10
#define EXAMPLE_MAX_STA_CONN		1

/* private variables ----------------------------------------------*/
static const char *TAG = "WIFI softAP";

/* private function prototypes ------------------------------------*/


/* public variables -----------------------------------------------*/

/**
  * @brief  WIFI 中断事件
  * @param  None
  * @retval None
  * @note   None
*/
static void wifi_event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data)
{
    if(event_id == WIFI_EVENT_AP_STACONNECTED)
    {
        tcpip_adapter_ip_info_t local_ip;
        if(tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &local_ip) == ESP_OK)
        {
            ESP_LOGI(TAG, "now_self_ip:"IPSTR,IP2STR(&local_ip.ip));
            ESP_LOGI(TAG, "now_self_netmask:"IPSTR,IP2STR(&local_ip.netmask));
            ESP_LOGI(TAG, "now_self_gw:"IPSTR,IP2STR(&local_ip.gw));
        }
    }
}

/**
  * @brief  WIFI Init
  * @param  None
  * @retval None
  * @note   None
*/
void WIFI_AP_Init(void)
{
	tcpip_adapter_init();

	ESP_ERROR_CHECK(esp_netif_init());
	ESP_ERROR_CHECK(esp_event_loop_create_default());

	ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,ESP_EVENT_ANY_ID,&wifi_event_handler,NULL,NULL));
	
	wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();

	ESP_ERROR_CHECK(esp_wifi_init(&cfg));

	wifi_config_t wifi_config = {
		.ap = {
			.ssid = EXAMPLE_ESP_WIFI_SSID,
			.ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),
			.channel = EXAMPLE_ESP_WIFI_CHANNEL,
			.password = EXAMPLE_ESP_WIFI_PASS,
			.max_connection = EXAMPLE_MAX_STA_CONN,
			.authmode = WIFI_AUTH_WPA_WPA2_PSK
		},
	};

	if (strlen(EXAMPLE_ESP_WIFI_PASS) == 0) {
		wifi_config.ap.authmode = WIFI_AUTH_OPEN;
	}

	ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));

	ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));

	ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config));

	ESP_ERROR_CHECK(esp_wifi_start());

}
